// components/calendar.js
const app = getApp()
Component({
  /**
   * 组件的属性列表
   */
  ready() {
    // const query = wx.createSelectorQuery()  // 获取dom元素
    // query.select('.header').boundingClientRect(function (res) {
    //   console.log(res)
    //   //这里返回元素自身的DOM属性
    // }).exec(function (rect) {
    //   console.log(rect)
    // });
  },
  properties: {

  },
  lifetimes: {
    attached: function () {
      let now = new Date();
      let year = now.getFullYear();
      let month = now.getMonth() + 1;
      let day = now.getDate();
      if (month < 10) {
        month = '0' + month
      }
      if (day < 10) {
        day = '0' + day
      }
      this.data.nowDay = '' + year + '-' + month + '-' + day
      this.data.nowYear = year
      this.data.nowMonth = month
      this.setData({
        year: year,
        month: month,
        isToday: '' + year + '-' + month + '-' + day
      })
      this.dateInit();
    },
    detached: function () {
      // 在组件实例被从页面节点树移除时执行
    },
  },
  /**
   * 组件的初始数据
   */
  data: {
    year: 0,
    month: 0,
    date: ['日', '一', '二', '三', '四', '五', '六'],
    dateArr: [],
    isToday: 0,
    isTodayWeek: false,
    todayIndex: 0,
    page: 0, // 当前滑动的页码
    totalPage: 0,  // 总滑动页码
    left: 0,  // 位移的距离
    width: 0, // 一个区域的宽度
    dateList: [],
    current: 0,
    total: 0,
    nowDay: "",  // 今天的时间
    nowDayIndex: "",  // 今天的时间的索引,
    selsecDay: [],// 选中的时间集合
    nowYear: "",
    nowMonth: "",
  },

  /**
   * 组件的方法列表
   */
  methods: {
    toDate(e) {
      let date = e.currentTarget.dataset.date
      let dateArr = this.data.dateArr
      let year = this.data.nowYear
      let month = this.data.nowMonth
      let nowDayIndex = this.data.nowDayIndex
      // console.log(date, year, month, nowDayIndex)
      try {
        for (let i = 0; i < dateArr.length; i++) {
          // 判断年份大小
          let el = dateArr[i];
          if (el.year < year) {
            return app.showToast("请选择正确的时间预约")
          } else if (el.year > year) {
            return this.jisuan(date)
          } else if (el.year == year && el.month < month) {
            return app.showToast("请选择正确的时间预约")
          } else if (el.year == year && el.month == month && date == el.isToday) {
            if (i >= nowDayIndex) {
              this.jisuan(date)
            } else {
              return app.showToast("请选择正确的时间预约")
            }
          } else if ((el.year = year || el.year > year) && el.month > month && date == el.isToday) {
            this.jisuan(date)
          }
        }
      } catch (error) {
        console.log(error)
      }




    },
    //  计算对应星期
    jisuan(date) {
      let that = this
      let dateList = this.data.dateList
      // console.log(dateList)
      for (let key in dateList) {
        // console.log(dateList[key])
        let arr = dateList[key]
        dateList[key]
        for (let i = 0; i < arr.length; i++) {
          if (arr[i].isToday == date) {
            that.setData({
              isToday: date,
              todayIndex: i
            })
          }
        }
      }
      this.triggerEvent('Calendar', date)
    },
    // 监听滑动结束
    bindanimationfinish(e) {
      this.setData({
        current: e.detail.current
      })
    },
    // 指示器
    select(e) {
      this.setData({
        current: e.currentTarget.dataset.index
      })
    },
    dateInit: function (setYear, setMonth) {
      var that = this
      //全部时间的月份都是按0~11基准，显示月份才+1
      let dateArr = [];                        //需要遍历的日历数组数据
      let arrLen = 0;                            //dateArr的数组长度
      let now = setYear ? new Date(setYear, setMonth) : new Date();
      let year = setYear || now.getFullYear();
      let nextYear = 0;
      let month = setMonth || now.getMonth();                    //没有+1方便后面计算当月总天数
      let nextMonth = (month + 1) > 11 ? 1 : (month + 1);
      let startWeek = new Date(year + '/' + (month + 1) + '/' + 1).getDay();                            //目标月1号对应的星期
      let dayNums = new Date(year, nextMonth, 0).getDate();                //获取目标月有多少天
      let obj = {};
      let num = 0;
      if (month + 1 > 11) {
        nextYear = year + 1;
        dayNums = new Date(nextYear, nextMonth, 0).getDate();
      }
      arrLen = startWeek + dayNums;
      for (let i = 0; i < arrLen; i++) {
        if (i >= startWeek) {
          num = i - startWeek + 1;
          let ms = month + 1
          let ds = num
          if (ms < 10) {
            ms = '0' + ms
          }
          if (ds < 10) {
            ds = '0' + ds
          }
          obj = {
            isToday: '' + year + '-' + (ms) + '-' + ds,
            dateNum: num,
            weight: 5,
            year: year,
            month: month + 1
          }
          if (this.data.nowDay == obj.isToday) {
            // obj.is_select = true
            this.data.nowDayIndex = i  // 记录当天的索引位置 用于判断选择时不选择逼当前月小的
            obj.nowDayIndex = i
          }
        } else {
          obj = {};
        }
        dateArr[i] = obj;
      }
      let n = dateArr.length / 7  // 除以一周
      let s = n.toString().substring(0, 1) * 1   // 总页数
      let arr = []   // 用于数据的替换
      let z = 0   // 添加对象的索引
      let total = {}  //总数居
      // 计算滚动需要的总页码
      if (n > s) {
        s = s + 1
      }
      dateArr.forEach((el, index) => {
        arr.push(el)
        if ((index + 1) % 7 == 0) {
          total[z] = arr
          z = z + 1
          arr = []
        }
        if (dateArr.length == index + 1 && (index + 1) % 7 !== 0) {
          total[z] = arr
          z = z + 1
          arr = []
        }
        if (el.isToday == that.data.isToday) {
          let yu = index / 7
          let quyu = yu.toString().substring(0, 1) * 1
          if (yu > quyu) {
            quyu + 1
          }
          this.setData({
            current: quyu
          })
        }
      })
      this.setData({
        dateArr: dateArr,
        totalPage: s,
        dateList: total,
      })

      let nowDate = new Date();
      let nowYear = nowDate.getFullYear();
      let nowMonth = nowDate.getMonth() + 1;
      let nowWeek = nowDate.getDay();
      let getYear = setYear || nowYear;
      let getMonth = setMonth >= 0 ? (setMonth + 1) : nowMonth;
      if (nowYear == getYear && nowMonth == getMonth) {
        this.setData({
          isTodayWeek: true,
          todayIndex: nowWeek
        })
      } else {
        this.setData({
          isTodayWeek: false,
          todayIndex: -1
        })
      }
    },
    lastMonth: function () {
      //全部时间的月份都是按0~11基准，显示月份才+1
      let year = this.data.month - 2 < 0 ? this.data.year - 1 : this.data.year;
      let month = this.data.month - 2 < 0 ? 11 : this.data.month - 2;
      this.setData({
        year: year,
        month: (month + 1)
      })
      this.dateInit(year, month);
      this.setData({
        current: 0
      })
      this.triggerEvent('initCurrent')
    },
    nextMonth: function () {
      //全部时间的月份都是按0~11基准，显示月份才+1
      let year = this.data.month > 11 ? this.data.year + 1 : this.data.year;
      let month = this.data.month > 11 ? 0 : this.data.month;
      this.setData({
        year: year,
        month: (month + 1)
      })
      this.dateInit(year, month);
      this.setData({
        current: 0
      })
      this.triggerEvent('initCurrent')
    }
  }
})
